<?php

declare(strict_types=1);

namespace App\Repository;
/**
 * 用户资料数据访问层
 * 作者 薛原
 * 日期 2025-10-17
 */
use Hyperf\Di\Annotation\Inject;
use App\Model\UserProfiles;
use Hyperf\Redis\Redis;

class UserProfilesRepository
{
    static string $cacheKey = "user_profiles";
    #[Inject]
    private UserProfiles $userProfilesModel;

    #[Inject]
    private Redis $redis;


    /**
     * 创建资料用户
     * @param array $data
     */
    public function create(array $data): void
    {
        $userProfiles = $this->userProfilesModel->create($data);
    }

    public function getDataById($id)
    {
        $cacheKey = self::$cacheKey.":{$id}";
        $ret = "";
        //这里redis连接失败就直接error错误，需考虑熔断机制
        try{
            $ret = $this->redis->get($cacheKey);
        }catch (\RedisException $e){
            $redis_live = false;
            echo "redis连接异常";
        }
        if($ret){
            return json_decode($ret);
        }
        $data = $this->userProfilesModel->where("user_id",$id)->first();
        if(!$data){
            return null;
        }
        $data = $data->toArray();
        if ($data) {
            if($redis_live){
                $this->redis->setex($cacheKey, 3600, json_encode($data)); // 缓存1小时
            }
        }
        return $data;
    }
    public function updateData($data,$id):void
    {
        $cacheKey = self::$cacheKey.":{$id}";
        $this->redis->del($cacheKey);
        $this->userProfilesModel->where("user_id",$id)->update($data);
    }
}